<template>
  <el-container>
    <jcx-search v-model:show-search="showSearch" :show-button="false" :query-form="queryParams"
                :power="'system:dept:lists'" @handle-reset-query="handleResetQuery" @handle-search="handleSearch">
      <el-col :span="12">
        <el-form-item label="部门名称" prop="name">
          <el-input placeholder="部门名称" clearable v-model="queryParams.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="启用状态" prop="enabled">
          <el-select placeholder="启用状态" clearable v-model="queryParams.enabled">
            <el-option key="1" label="启用" :value="true"></el-option>
            <el-option key="0" label="停用" :value="false"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </jcx-search>
    <el-header>
      <div class="left-panel">
        <div class="left-panel-search" v-if="showSearch">
          <el-button type="primary" plain icon="el-icon-search" @click="handleSearch"
                     v-power="'system:dept:lists'"></el-button>
          <el-button type="info" plain icon="el-icon-refresh" @click="handleResetQuery"></el-button>
        </div>
      </div>
      <div class="right-panel">
        <jcx-table-bar :column-list="columnList" v-model:config="config" v-model:show-search="showSearch"
                       @query-table="getList"></jcx-table-bar>
      </div>
    </el-header>
    <el-main class="no-padding">
      <el-table style="width: 100%" ref="table" row-key="id" v-loading="loading" :data="dataList"
                :stripe="config.stripe" :border="config.border" :size="config.size"
                @selection-change="handleSelectionChange"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column type="selection"></el-table-column>
        <template v-for="(column, index) in columnList" :key="index">
          <el-table-column v-if="!column.hide" :label="column.label" :prop="column.prop" :align="column.align"
                           :width="column.width" :fixed="column.fixed">
            <template #default="scope">
              <jcx-render-column v-if="column.render" :scope="scope" :render="column.render"></jcx-render-column>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </el-main>
    <el-footer>
      <div class="jcx-table-page">
        <div class="jcx-table-do">
          <el-button type="primary" plain icon="el-icon-plus" @click="handleAddClick"
                     v-powers="['system:user:lists' , 'system:dept:lists' , 'system:dept:add']"></el-button>
          <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple"
                     @click="handleDeleteClick" v-power="'system:dept:del'"></el-button>
          <el-button type="warning" plain icon="el-icon-edit" :disabled="single" @click="handleEditClick"
                     v-powers="['system:user:lists' , 'system:dept:lists' , 'system:dept:info' , 'system:dept:edit']"></el-button>
        </div>
      </div>
    </el-footer>

    <el-dialog destroy-on-close append-to-body :close-on-click-modal="false" width="1080px" :title="title"
               v-model="open" @closed="handleCancel">
      <dept-form ref="deptFormRef" :form="form"></dept-form>
      <template #footer>
        <el-button plain :type="form.id ? 'warning' : 'primary'" :loading="saving" @click="handleSubmitForm"
                   v-power="form.id ? 'system:dept:edit' : 'system:dept:add'">{{ form.id ? '修 改' : '保 存' }}
        </el-button>
        <el-button plain type="info" @click="handleCancel">取 消</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import {onMounted, ref} from "vue";
import deptForm from "./form.vue";
import deptApi from "@/api/system/dept";
import renderUtil from "@/utils/render";
import modal from "@/utils/modal";
import tree from "@/utils/tree";

// 是否显示搜索栏
const showSearch = ref(true);
// 查询条件
const queryParams = ref({
  name: null,
  enabled: null,
});
// 表格配置
const config = ref({
  // 表格大小
  size: "default",
  // 表格边框
  border: true,
  // 表格斑马图纹
  stripe: true
});
// 表格数据列表
const dataList = ref([]);
// 表格列数据
const columnList = ref([
  {
    label: '部门标识',
    prop: 'code',
    hide: false,
    align: 'center'
  },
  {
    label: '部门名称',
    prop: 'name',
    hide: false,
    align: 'center'
  },
  {
    label: '部门负责人',
    prop: 'userName',
    hide: false,
    align: 'center'
  },
  {
    label: '部门联系方式',
    prop: 'phone',
    hide: false,
    align: 'center'
  },
  {
    label: '部门联系邮箱',
    prop: 'email',
    hide: false,
    align: 'center'
  },
  {
    label: '是否启用',
    prop: 'enabled',
    hide: false,
    align: 'center',
    render: (h, row) => {
      return renderUtil.renderYesOrNo(row.enabled, '启用', '停用');
    }
  },
  {
    label: '排序',
    prop: 'sort',
    hide: false,
    align: 'center'
  },
  {
    label: '创建时间',
    prop: 'createTime',
    hide: false,
    align: 'center'
  },
  {
    label: '备注',
    prop: 'remark',
    hide: false,
    align: 'center'
  },
  {
    label: '操作',
    prop: 'operation',
    hide: false,
    align: 'center',
    render: (h, row) => {
      return renderUtil.renderOperation(row, handleDeleteClick, 'system:dept:del', handleEditClick, ['system:user:lists' , 'system:dept:lists' , 'system:dept:info' , 'system:dept:edit']);
    }
  },
]);
// 表格中被选中的数据列表
const selectList = ref([]);
// 加载动画
const loading = ref(false);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 表单组件
const deptFormRef = ref(null);
// 保存状态
const saving = ref(false);
// 弹出层状态
const open = ref(false);
// 弹出层标题
const title = ref('新增部门');
// 表单数据
const form = ref({
  id: null,
  code: null,
  name: null,
  parentId: null,
  userId: null,
  phone: null,
  email: null,
  sort: null,
  remark: null,
  enabled: null
});

// 查询按钮触发方法
const handleSearch = () => {
  getList();
}

// 重置查询条件触发按钮
const handleResetQuery = () => {
  queryParams.value = {
    name: null,
    enabled: null,
  };
  handleSearch();
}

// 获取数据方法
const getList = () => {
  loading.value = true;
  deptApi.lists.get(queryParams.value).then(response => {
    dataList.value = tree.buildTree(response.data.list);
    loading.value = false;
  })
}

// 表格选中触发方法
const handleSelectionChange = (selection) => {
  selectList.value = selection.map(item => item);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮方法
const handleAddClick = () => {
  title.value = '新增部门';
  open.value = true;
}

// 删除按钮方法
const handleDeleteClick = (row) => {
  const idList = row.id ? [row.id] : selectList.value.map(item => item.id);
  modal.confirm(`确定删除选中的 ${idList.length} 项吗？`).then(() => {
    deptApi.del.delete(idList).then(response => {
      if (response.status) {
        modal.successMessage(response.message);
        getList();
      } else {
        modal.errorMessage(response.message);
      }
    });
  }).catch(() => {
    modal.infoMessage("用户取消操作");
  })
}

// 编辑按钮方法
const handleEditClick = (row) => {
  const id = row.id || selectList.value[0].id;
  deptApi.info.get(id, true).then(response => {
    form.value = response.data;
    title.value = '编辑部门';
    open.value = true;
  });
}

// 重置 form
const resetForm = (formEl) => {
  form.value = {
    id: null,
    code: null,
    name: null,
    parentId: null,
    userId: null,
    phone: null,
    email: null,
    sort: null,
    remark: null,
    enabled: null
  };
  if (!formEl) return;
  formEl.resetFields();
}

// 关闭弹窗
const handleCancel = () => {
  resetForm(deptFormRef.value.getFormRef());
  open.value = false;
}

// 弹窗提交
const handleSubmitForm = () => {
  saving.value = true;
  const formRef = deptFormRef.value.getFormRef();
  formRef.validate(valid => {
    if (valid) {
      if (form.value.id) {
        // 修改
        deptApi.edit.put(form.value).then(response => {
          modal.message(response.message, {type: response.status ? 'success' : 'error'})
          saving.value = false;
          if (response.status) {
            handleCancel();
            handleSearch();
          }
        })
      } else {
        // 新增
        deptApi.add.post(form.value).then(response => {
          modal.message(response.message, {type: response.status ? 'success' : 'error'})
          saving.value = false;
          if (response.status) {
            handleCancel();
            handleSearch();
          }
        })
      }
    } else {
      saving.value = false;
      modal.warningMessage("表单校验不通过");
    }
  });
}

// 页面加载时触发方法
onMounted(() => {
  getList();
})
</script>

<style scoped lang="scss">
</style>
